package cn.taobaoke.restful.interceptor;

import cn.taobaoke.restful.exception.TBKException;
import cn.taobaoke.restful.service.AdminService;
//import cn.taobaoke.restful.service.AgentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author yangzuo
 * @since 2017-03-12
 */
@Component
public class ApiLoginInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private AdminService adminService;

//    @Autowired
//    private AgentService agentService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        AdminEntity admin = (AdminEntity) request.getSession().getAttribute(Constants.LoginUser.ADMIN);
//        AgentEntity agent = (AgentEntity) request.getSession().getAttribute(Constants.LoginUser.AGENT);
//
//        for (Cookie cookie : request.getCookies()) {
//            if (cookie.getName() == "tbk_user_token") {
//                String token = cookie.getValue();
//                admin = adminService.getByToken(token);
//                if (admin != null) {
//                    agent = agentService.getByToken(token);
//                }
//            }
//        }
//
//        if (admin == null && agent == null) {
//            error(new TBKException("尚未登录,请先登录"), response);
//            return false;
//        }
//
//        // 权限验证
//        Auth auth = ((HandlerMethod) handler).getMethodAnnotation(Auth.class);
//        if (auth == null) return true;      // 管理员/代理都可以访问
//
//        // 权限检查
//        Auth.AuthType[] authTypes = auth.type();
//        if (admin != null && isAuthTypeIn(Auth.AuthType.ADMIN, authTypes)) {
//            return true;
//        }
//        if (agent != null && isAuthTypeIn(Auth.AuthType.AGENT, authTypes)) {
//            return true;
//        }
//
//        error(new TBKException("权限不够,无权调用该接口"), response);
//        return false;
        return true;
    }

    private boolean isAuthTypeIn(Auth.AuthType type, Auth.AuthType[] types) {
        for (Auth.AuthType t : types) {
            if (t == type) return true;
        }
        return false;
    }

    private void error(TBKException error, HttpServletResponse response) {
        PrintWriter writer;
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json;charset=UTF-8");
            writer = response.getWriter();
            writer.write(error.toJson());
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
